package org.abacus.jdbc.util;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.abacus.http.HttpException;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.tree.DefaultElement;

public class XMLParserUtil {

	public static Map<String, String> getJdbc(String xmlFileName) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(xmlFileName);
			Element element = document.getRootElement();
			List<?> list = element.selectNodes("jdbc");
			Iterator<?> iterator = list.iterator();
			DefaultElement defaultElement = null;
			Attribute attribute = null;
			while (iterator.hasNext()) {
				defaultElement = (DefaultElement) iterator.next();
				attribute = defaultElement.attribute("selected");
				if (null != attribute) {
					String text = attribute.getText();
					if ("true".equals(text)) {
						int size = defaultElement.attributeCount();
						for (int i = 0; i < size; i++) {
							attribute = defaultElement.attribute(i);
							map.put(attribute.getName(), attribute.getText());
						}
						break;
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

	public static void addJdbc(String xmlFileName, Map<String, String> map) {
		if (null != map && map.size() > 0) {
			try {
				SAXReader saxReader = new SAXReader();
				Document document = saxReader.read(xmlFileName);
				Element element = document.getRootElement();
				Element jdbc = element.addElement("jdbc");
				for (Entry<String, String> entry : map.entrySet()) {
					jdbc.addAttribute(entry.getKey(), entry.getValue());
				}
				XMLWriter output = new XMLWriter();
				output.write(document);
				output.flush();
				output.close();
			} catch (DocumentException e) {
				throw new HttpException(e.getMessage(), e, null);
			} catch (IOException e) {
				throw new HttpException(e.getMessage(), e, null);
			}
		}
	}

	public static void main(String[] argv) {
		try {
			String xmlFileName = XMLParserUtil.class.getClassLoader().getResource("jdbc.xaml").toURI().toString();
			// System.out.println(xmlFileName);
			Map<String, String> map = XMLParserUtil.getJdbc(xmlFileName);
			// System.out.println(map);
			XMLParserUtil.addJdbc(xmlFileName, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
